<script setup lang="ts">
defineOptions({
  name: 'UserAvatar',
})

import { ref, computed } from 'vue'
import { PhSignIn, PhUser, PhGear, PhSignOut } from '@phosphor-icons/vue'

interface User {
  id: string
  name: string
  email: string
  avatar?: string
  role?: string
}

interface Props {
  user?: User | null
  size?: 'sm' | 'md' | 'lg'
  showDropdown?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  user: null,
  size: 'md',
  showDropdown: true,
})

const emit = defineEmits<{
  login: []
  logout: []
  profile: []
  settings: []
}>()

// 下拉菜单状态
const isDropdownOpen = ref(false)

// 尺寸配置
const sizeConfig = {
  sm: { avatar: 'w-8 h-8', text: 'text-sm' },
  md: { avatar: 'w-10 h-10', text: 'text-base' },
  lg: { avatar: 'w-12 h-12', text: 'text-lg' },
}

const currentSize = computed(() => sizeConfig[props.size])

// 用户名首字母
const userInitial = computed(() => {
  if (!props.user?.name) return 'U'
  return props.user.name.charAt(0).toUpperCase()
})

// 头像颜色（基于用户名生成）
const avatarColor = computed(() => {
  if (!props.user?.name) return 'from-primary to-secondary'

  const colors = [
    'from-red-500 to-pink-500',
    'from-blue-500 to-cyan-500',
    'from-green-500 to-emerald-500',
    'from-purple-500 to-violet-500',
    'from-orange-500 to-yellow-500',
    'from-indigo-500 to-blue-500',
    'from-pink-500 to-rose-500',
    'from-teal-500 to-green-500',
  ]

  const hash = props.user.name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  return colors[hash % colors.length]
})

// 处理登录
const handleLogin = () => {
  emit('login')
}

// 处理登出
const handleLogout = () => {
  isDropdownOpen.value = false
  emit('logout')
}

// 处理个人资料
const handleProfile = () => {
  isDropdownOpen.value = false
  emit('profile')
}

// 处理设置
const handleSettings = () => {
  isDropdownOpen.value = false
  emit('settings')
}

// 切换下拉菜单
const toggleDropdown = () => {
  if (props.showDropdown && props.user) {
    isDropdownOpen.value = !isDropdownOpen.value
  }
}

// 关闭下拉菜单
const closeDropdown = () => {
  isDropdownOpen.value = false
}
</script>

<template>
  <div class="user-avatar relative">
    <!-- 未登录状态 - 登录按钮 -->
    <button
      v-if="!user"
      @click="handleLogin"
      class="btn btn-primary btn-sm gap-2 hover:scale-105 transform transition-all duration-200 hover:shadow-lg"
    >
      <PhSignIn :size="16" />
      <span class="hidden sm:inline">登录</span>
    </button>

    <!-- 已登录状态 - 用户头像 -->
    <div v-else class="relative">
      <button
        @click="toggleDropdown"
        :class="[
          'avatar-button relative overflow-hidden rounded-full border-2 border-transparent hover:border-primary/30 transition-all duration-300 transform hover:scale-110 hover:shadow-lg',
          currentSize.avatar,
          showDropdown ? 'cursor-pointer' : 'cursor-default',
        ]"
      >
        <!-- 用户头像图片 -->
        <img
          v-if="user.avatar"
          :src="user.avatar"
          :alt="user.name"
          class="w-full h-full object-cover"
        />

        <!-- 默认头像（用户名首字母） -->
        <div
          v-else
          :class="[
            'w-full h-full flex items-center justify-center text-white font-bold bg-gradient-to-br',
            avatarColor,
            currentSize.text,
          ]"
        >
          {{ userInitial }}
        </div>

        <!-- 在线状态指示器 -->
        <div
          class="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 border-2 border-base-100 rounded-full animate-pulse"
        ></div>
      </button>

      <!-- 下拉菜单 -->
      <Transition
        enter-active-class="transition-all duration-200 ease-out"
        enter-from-class="opacity-0 scale-95 -translate-y-2"
        enter-to-class="opacity-100 scale-100 translate-y-0"
        leave-active-class="transition-all duration-150 ease-in"
        leave-from-class="opacity-100 scale-100 translate-y-0"
        leave-to-class="opacity-0 scale-95 -translate-y-2"
      >
        <div
          v-if="isDropdownOpen && showDropdown"
          class="dropdown-menu absolute right-0 top-full mt-2 w-64 bg-base-100 rounded-2xl shadow-2xl border border-base-300/50 backdrop-blur-md z-[70] overflow-hidden"
        >
          <!-- 用户信息头部 -->
          <div
            class="p-4 bg-gradient-to-r from-primary/10 to-secondary/10 border-b border-base-300/30"
          >
            <div class="flex items-center gap-3">
              <div :class="['rounded-full overflow-hidden', currentSize.avatar]">
                <img
                  v-if="user.avatar"
                  :src="user.avatar"
                  :alt="user.name"
                  class="w-full h-full object-cover"
                />
                <div
                  v-else
                  :class="[
                    'w-full h-full flex items-center justify-center text-white font-bold bg-gradient-to-br',
                    avatarColor,
                    currentSize.text,
                  ]"
                >
                  {{ userInitial }}
                </div>
              </div>
              <div class="flex-1 min-w-0">
                <p class="font-semibold text-base-content truncate">{{ user.name }}</p>
                <p class="text-sm text-base-content/60 truncate">{{ user.email }}</p>
                <span
                  v-if="user.role"
                  class="inline-block px-2 py-0.5 text-xs bg-primary/20 text-primary rounded-full mt-1"
                >
                  {{ user.role }}
                </span>
              </div>
            </div>
          </div>

          <!-- 菜单项 -->
          <div class="p-2">
            <button
              @click="handleProfile"
              class="menu-item w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-base-200/70 rounded-xl transition-all duration-200 group"
            >
              <PhUser
                :size="18"
                class="text-base-content/70 group-hover:text-primary transition-colors"
              />
              <span class="text-base-content group-hover:text-primary transition-colors"
                >个人资料</span
              >
            </button>

            <button
              @click="handleSettings"
              class="menu-item w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-base-200/70 rounded-xl transition-all duration-200 group"
            >
              <PhGear
                :size="18"
                class="text-base-content/70 group-hover:text-primary transition-colors"
              />
              <span class="text-base-content group-hover:text-primary transition-colors">设置</span>
            </button>

            <div class="divider my-2"></div>

            <button
              @click="handleLogout"
              class="menu-item w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-error/10 rounded-xl transition-all duration-200 group"
            >
              <PhSignOut :size="18" class="text-error group-hover:text-error transition-colors" />
              <span class="text-error group-hover:text-error transition-colors">退出登录</span>
            </button>
          </div>
        </div>
      </Transition>

      <!-- 点击外部关闭下拉菜单 -->
      <div v-if="isDropdownOpen" @click="closeDropdown" class="fixed inset-0 z-[65]"></div>
    </div>
  </div>
</template>

<style scoped>
.avatar-button {
  position: relative;
}

.avatar-button::before {
  content: '';
  position: absolute;
  inset: -2px;
  background: linear-gradient(45deg, hsl(var(--p)), hsl(var(--s)));
  border-radius: inherit;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.avatar-button:hover::before {
  opacity: 0.2;
}

.dropdown-menu {
  animation: slideDown 0.2s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-8px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.menu-item {
  position: relative;
  overflow: hidden;
}

.menu-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 0;
  height: 100%;
  background: linear-gradient(90deg, hsl(var(--p) / 0.1), transparent);
  transition: width 0.3s ease;
}

.menu-item:hover::before {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .dropdown-menu {
    width: 240px;
  }
}

/* 无障碍访问 */
@media (prefers-reduced-motion: reduce) {
  .avatar-button,
  .menu-item,
  .dropdown-menu {
    transition: none !important;
    animation: none !important;
  }
}
</style>
